//
//  HomeViewController.m
//  Bracelet
//
//  Created by jing zhao on 2/16/15.
//  Copyright (c) 2015 jing zhao. All rights reserved.
//

#import "HomeViewController.h"
#import "MBProgressHUD.h"
#import "MyWorkoutViewController.h"
#import "SynchronizationView.h"

#import "LoadingPageController.h"
#import "CharityWalkathonController.h"
#import "BluetoothConfirmView.h"
#import "AppDelegate.h"
#import "AlertView.h"
#import "MainViewController.h"
#import "ProgressingView.h"
#import "Reachability.h"
#import "Syncdata.h"
#import "UIRefreshTableView.h"

#define HSBC_DATA_SERVER 100
#define SHOW_SATURDAY_MESSAGE @"showSaturdayMessage"
#define SHOW_SUNDAY_MESSAGE @"showSundayMessage"
#define LAST_SYNC_TIME @"lastSyncTime"

@interface HomeViewController ()<DelegateChangeHomeController>
//用来转换的View
@property (weak, nonatomic) IBOutlet UIView *viewChange;
//用来装要换的View;
@property (weak, nonatomic) IBOutlet UIView *transitionView;
//所有的ViewController
@property (strong, nonatomic)NSArray *arrayViewControllers;

@property (strong, nonatomic)NSArray *arrayLabel;
@property (weak, nonatomic) IBOutlet UILabel *ui_labelWorkout;
@property (weak, nonatomic) IBOutlet UILabel *ui_mycity;
@property (weak, nonatomic) IBOutlet UILabel *ui_hbcn;
@property (assign, nonatomic) BOOL isAuthorizationPageShowed;
@property (strong, nonatomic)CBCentralManager *centralManager;

@property (assign, nonatomic) BOOL isUploadingData;
@property (strong, nonatomic) ProgressingView * uploadingAlert;

@property (unsafe_unretained, nonatomic)BOOL    isFirstSynSuccess;
@property (strong, nonatomic) NSDate *currentSynDate;
@property (strong, nonatomic) NSDate *lastSynDate;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *menuHorizontalContraints;

@end

@implementation HomeViewController

- (IBAction)showMenu
{
    [self.frostedViewController presentMenuViewController];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"HomeViewController--viewDidLoad!");
  
    _loadingPage = nil;
    
    // fix the menu button issue
    if([[[UIDevice currentDevice] systemVersion] floatValue]<8.0){
        _menuHorizontalContraints.constant = 0;
    }
    
    //注册通知
  
  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(presentCharityWalkathonPage:) name:@"CharityWalkathon" object:nil];
  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshWalkout) name:@"refreshWalkout" object:nil];
  
    self.arrayLabel = @[self.ui_labelWorkout,self.ui_mycity,self.ui_hbcn];
    MyWorkoutViewController *myWorkController = [[MyWorkoutViewController alloc]initWithNibName:@"MyWorkoutViewController" bundle:nil];
    myWorkController.delegateChangeHomeController =self;
    [myWorkController setTitle:@"My Workout" andwithType:STYPE_WORKOUT];
    
    MyWorkoutViewController *cityController = [[MyWorkoutViewController alloc]initWithNibName:@"MyWorkoutViewController" bundle:nil];
    cityController.delegateChangeHomeController =self;
    [cityController setTitle:@"My City" andwithType:STYPE_MYCITY];
    
    MyWorkoutViewController *hbcnController = [[MyWorkoutViewController alloc]initWithNibName:@"MyWorkoutViewController" bundle:nil];
    hbcnController.delegateChangeHomeController = self;
    [hbcnController setTitle:@"HBCN" andwithType:STYPE_HBCN];
    self.arrayViewControllers = @[myWorkController,cityController,hbcnController];
    
    [self transitionViewDisplayIndex:0];
  

    _blueToothStatus = CBCentralManagerStatePoweredOn;
    _isBlueErrorShow = NO;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(isShowReminder) name:NOTIFICATION_APP_BECOME_ACTIVE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(isHiddenInfoButton:) name:NOTIFICATION_BRACELET_ISFIRSTPAGE object:nil];
    
    _loadingPage = [[LoadingPageController alloc]initWithNibName:@"LoadingPageController" bundle:nil];
    _loadingPage.view.frame = self.view.bounds;
    [self addChildViewController:_loadingPage];
    [self.view addSubview:_loadingPage.view];
    
    _isSearchingBracelet = NO;
    //[bongSDK enableDebugMode:YES];
    //授权手环
    
    //设置bongSDK 代理
    [bongSDK addDelegate:self];
    
    if ([bongSDK isAuthorizationValide]) {
        [bongSDK run];
        [self performSelector:@selector(removeLoadingPage) withObject:nil afterDelay:10.0];
        return;
        
    }else {
        [bongSDK requstAuthorization];
        _requestAuthorization = YES;
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
  //第一次打开或者每次蓝牙状态改变都会调用这个函数
    _blueToothStatus = central.state;
  if(central.state==CBCentralManagerStatePoweredOn){
    NSLog(@"蓝牙设备开着");
      if([bongSDK isAuthorizationValide]){
          
          double delayInSeconds = 0.5;
          dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
          dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
              //code to be executed on the main queue after delay
              [bongSDK run];
          });
          
      }
  }
  else{
       _isBlueErrorShow = NO;
      if ( _button.tag == 0) {
          if (_pageIndex == 0 || _pageIndex == 1) {
            if([bongSDK isAuthorizationValide]){
              [self showBlueToothError];
             }
          }
      }else{
          
      }

      NSLog(@"蓝牙设备关着");
  }
}

- (void)showBlueToothError{
    if (!_isBlueErrorShow) {
        BluetoothConfirmView * alert = [BluetoothConfirmView shareInstance];
        alert = [[[NSBundle mainBundle]loadNibNamed:@"BluetoothConfirmView" owner:self options:nil] lastObject];
        alert.confirmTitle.text = @"Bluetooth is off";
        alert.confirmMessage.text = @"Please turn on bluetooth to allow connection to Bong.\n \n \n ";
        alert.frame = [[UIScreen mainScreen] bounds];
        [self.view addSubview:alert];
        _isBlueErrorShow = YES;
    }
 
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
-(void)viewDidDisappear:(BOOL)animated{
  NSLog(@"viewDidDisappear");
  self.isAuthorizationPageShowed = YES;

}
-(void)viewDidAppear:(BOOL)animated{
  if (self.isAuthorizationPageShowed) {
    [self performSelector:@selector(removeLoadingPage) withObject:nil afterDelay:10.0];
    [self performSelector:@selector(isShowNewsroom) withObject:nil afterDelay:6.0];
  }
}
- (void)isShowNewsroom{
    if (_requestAuthorization && ![bongSDK isAuthorizationValide]) {
        [self showBackNewsRoomAlert];
    }
}
- (void)showBackNewsRoomAlert{
    AlertView * alert = [AlertView shareInstance];
    alert = [[[NSBundle mainBundle]loadNibNamed:@"AlertView" owner:self options:nil] lastObject];
    alert.alertTitle.text = @"Oops!";
    alert.alertMessage.text = @"You need to provide your Bong profile first before using the Walkathon service. Make sure you have the profile ready then try again.";
    alert.alertDelegate = self;
    alert.frame = [[UIScreen mainScreen] bounds];
    [self.view addSubview:alert];
}
#pragma mark -- alert view
- (void)alertButtonPressed:(AlertView *)alertView{
      [self showNewsroom];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)prefersStatusBarHidden{
    //return YES;
    return NO;
}
-(void)removeLoadingPage{
    if ([bongSDK isAuthorizationValide]) {
          [[NSNotificationCenter defaultCenter]postNotificationName:@"RemoveLoadingPage" object:nil];
    }
  //蓝牙设置代理
  self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
}
#pragma mark - bongSDKDelegate

- (void)bongSDKDidAutherize:(bongSDKErrorCode)errorCode {
    NSLog(@"授权回调： errorCode %d", errorCode);
    if (errorCode == bongSDKErrorCodeNone) {
        NSLog(@"授权获取成功 errorCode %d", errorCode);
        _requestAuthorization = NO;
    }else{
        [self isShowNewsroom];
    }
    [self performSelector:@selector(removeLoadingPage) withObject:nil afterDelay:1.0];
    //[bongSDK removeDelegate:self];
    [bongSDK run];
}
- (void)bongSDKDidRun:(bongSDKErrorCode)code{
    if (code == bongSDKErrorCodeNone) {
        _isSearchingBracelet = YES;
    }
}
- (void)bongSDKDidStop:(bongSDKErrorCode)code{
    if (code == bongSDKErrorCodeNone) {
        _isSearchingBracelet = NO;
    }

}
- (void)showNewsroom{
    [(MainViewController *)[(AppDelegate *)[[UIApplication sharedApplication] delegate] viewController] changeMenuBackFromGreenWithMenuId :@"push_newsroom"];
    
    NSLog(@"fail Autherize, return to newsroom ");
    [[(AppDelegate *)[[UIApplication sharedApplication] delegate] viewController].navigationController popViewControllerAnimated:NO];
}
-(void)viewWillLayoutSubviews{
    NSLog(@"HomeViewController--viewWillLayoutSubviews!");
}
-(void)viewDidLayoutSubviews{
    NSLog(@"HomeViewController--viewDidLayoutSubviews!");
    [self isShowReminder];
}

/***********************************
 transition view controller
 **********************************/
-(void)refreshWalkout{
  [self transitionViewDisplayIndex:0];
}
-(void)transitionViewDisplayIndex:(NSInteger)index
{
    //隐藏加载workout City HBCN
    MyWorkoutViewController *targetViewController = [self.arrayViewControllers objectAtIndex:index];
    [_transitionView.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [obj setHidden:YES];
    }];
    targetViewController.view.hidden = NO;
    if (![targetViewController.view isDescendantOfView:_transitionView]) {
        //targetViewController.view.frame = _transitionView.frame;
        targetViewController.view.frame = CGRectMake(_transitionView.frame.origin.x, 0, _transitionView.frame.size.width, _transitionView.frame.size.height);
        [_transitionView addSubview:targetViewController.view];
      [targetViewController updateOneSectionData];
    }
    else
    {
        [targetViewController updateOneSectionData];
    }
    [targetViewController scrollToIndex:0];
    
    //通知外面是哪个workout City HBCN
    [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_BRACELET_ISWORKOUT object:nil userInfo:@{NOTIFICATION_BRACELET_CONTROLLERTYPE:[NSString stringWithFormat:@"%ld",(long)index]}];
    //并在第一次的时候通知是哪个Total week history
    [targetViewController.ui_scrollView notifyCurrentPage];

    //替换选择workout City HBCN 页面 的label
    for (UILabel *label in self.arrayLabel) {
        label.font = [UIFont fontWithName:@"Univers Next for HSBC W01 Lt" size:14];
        
    }
    UILabel *label = [self.arrayLabel objectAtIndex:index];
    label.font = [UIFont fontWithName:@"Univers Next for HSBC W01 Rg" size:16];
}
- (IBAction)cancel:(id)sender {
        self.viewChange.hidden = YES;
}

- (IBAction)buttonChangeTransmitDisplay:(id)sender {
    
    _button =(UIButton*)sender;
    
    [self transitionViewDisplayIndex:_button.tag];
    self.viewChange.hidden = YES;
}

-(void)changeHomeController
{
    self.viewChange.hidden = NO;
}


-(void)presentCharityWalkathonPage:(NSNotification *)noti{
  CharityWalkathonController *charity = [[CharityWalkathonController alloc]initWithNibName:@"CharityWalkathonController" bundle:nil];
  [self presentViewController:charity animated:YES completion:^{
    
  }];
}
#pragma mark -- 
- (void)isHiddenInfoButton:(NSNotification *)notification{
    NSDictionary *dic = notification.userInfo;
    _pageIndex = [[dic objectForKey:NOTIFICATION_BRACELET_PAGE ] integerValue];
    MyWorkoutViewController *targetViewController = [self.arrayViewControllers objectAtIndex:_button.tag];
    if (_button.tag == 0) {
        if (_pageIndex == 0 || _pageIndex == 1) {
            if (_blueToothStatus != CBCentralManagerStatePoweredOn){
                    [self showBlueToothError];
                
            }
            targetViewController.infoButton.hidden = NO;
            if (!_isSearchingBracelet) {
                [bongSDK run];
            }
            
        }else{
            targetViewController.infoButton.hidden = YES;
                [bongSDK stop];
        }
        
    }else{
            targetViewController.infoButton.hidden = YES;
            [bongSDK stop];
    }
            
}

- (void)updateViewContent:(NSInteger)arrIndex pageIndex:(NSInteger)pageIndex{
    if (arrIndex <=[self.arrayViewControllers count] ) {
        MyWorkoutViewController *targetViewController = [self.arrayViewControllers objectAtIndex:_button.tag];
        if (pageIndex <= [targetViewController.ui_scrollView.subviews count]) {
            RefreshView *view = [targetViewController.ui_scrollView.subviews objectAtIndex:pageIndex];
            [view updateNetwork];
        }
    }
}
#pragma mark -- info message
- (BOOL)isDay:(NSInteger)week_{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:now];
    NSInteger week = [comps weekday];
    if (week  == week_) {
        return YES;
    }
    return NO;
}
- (NSString *)nowMonthDay{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:now];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    NSString *str = [NSString stringWithFormat:@"%d %d",month,day];
    return str;
}

- (void)isShowStaturdayMessage{
    if( [self isDay:7]){
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *str = [userDefaults objectForKey:SHOW_SATURDAY_MESSAGE];
        if ([[self nowMonthDay] isEqualToString:str]) {
            // already show
        }else{
            [self performSelector:@selector(showSaturdayMessage) withObject:nil afterDelay:0.5];
            [userDefaults setObject:[self nowMonthDay] forKey:SHOW_SATURDAY_MESSAGE];
            [userDefaults synchronize];
        }
    }
}

- (void)isShowSundayMessage{
    if( [self isDay:1]){
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *str = [userDefaults objectForKey:SHOW_SUNDAY_MESSAGE];
        if ([[self nowMonthDay] isEqualToString:str]) {
            // already show
        }else{
            [self performSelector:@selector(showSundayMessage) withObject:nil afterDelay:0.5];
            [userDefaults setObject:[self nowMonthDay] forKey:SHOW_SUNDAY_MESSAGE];
            [userDefaults synchronize];
        }
    }
}

- (void)showSaturdayMessage{
    AlertView * alert = [AlertView shareInstance];
    alert = [[[NSBundle mainBundle]loadNibNamed:@"AlertView" owner:self options:nil] lastObject];
    NSString *userName =[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    alert.alertTitle.text = @"Reminder";
    alert.alertMessage.text = [NSString stringWithFormat:@"Hi %@, don't forget to synchronise your wrist strap data.",userName];
    alert.frame = [[UIScreen mainScreen] bounds];
    [self.view addSubview:alert];
}

- (void)showSundayMessage{
    AlertView * alert = [AlertView shareInstance];
    NSString *userName =[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    alert = [[[NSBundle mainBundle]loadNibNamed:@"AlertView" owner:self options:nil] lastObject];
    alert.alertTitle.text = @"A new week has started";
    alert.alertMessage.text = [NSString stringWithFormat:@"Hi %@, we are looking forward to your walkthon performance in this new week!",userName];
    alert.frame = [[UIScreen mainScreen] bounds];
    [self.view addSubview:alert];
}

- (void)isShowReminder{
    if ([bongSDK isAuthorizationValide]) {
        [self isShowStaturdayMessage];
        [self isShowSundayMessage];
    }
}

#pragma mark - bongSDKDelegate
- (void)bongSDKDidScanbongIIWithPressYesKey:(YESKeyTouchType)touchType {

    if (touchType == YESKeyTouchTypeLong) {
        NSLog(@"长按");
        [self fetchbongIIData];
    } else if (touchType == YESKeyTouchTypeShort) {
        NSLog(@"短按");
        [self fetchbongIIData];
    } else {
        NSLog(@"Yes!");
        [self fetchbongIIData];
    }
}
/*
- (void)bongSDKDidScanbongIIWithPressYesKey:(YESKeyTouchType)touchType {
    self.isFirstSynSuccess = NO;
    NSArray *dateArr = [self getStartAndEndDates];
    NSDate *beginDate = [dateArr objectAtIndex:0];
    NSDate *endDate = [dateArr objectAtIndex:1];
    
    if (touchType == YESKeyTouchTypeLong) {
        NSLog(@"长按");
        [self fetachbongIIData:beginDate endDate:endDate];
    } else if (touchType == YESKeyTouchTypeShort) {
        NSLog(@"短按");
        [self fetachbongIIData:beginDate endDate:endDate];
    } else {
        NSLog(@"Yes!");
        [self fetachbongIIData:beginDate endDate:endDate];
    }
}
*/
- (void)bongSDKDataFetchStatusDidChange:(bongSDKDataFetchStatus)status error:(NSError *)error {
    
    NSLog(@"手环数据同步状态更新 %d error %@", status, error);
    if (status == bongSDKDataFetchStatusSucceed ||
        status == bongSDKDataFetchStatusFailed) {
    }
    if (!self.isUploadingData) {
        self.uploadingAlert = [ProgressingView shareInstance];
        _uploadingAlert = [[[NSBundle mainBundle]loadNibNamed:@"ProgressingView" owner:self options:nil] lastObject];
        _uploadingAlert.frame = [[UIScreen mainScreen] bounds];
        [self.view addSubview:_uploadingAlert];
        self.isUploadingData = YES;
    }
    
    if(status == bongSDKDataFetchStatusConnecting){
        _uploadingAlert.progressMessage.text = @"Connecting...";
    }
    if (status == bongSDKDataFetchStatusFetching) {
        _uploadingAlert.progressMessage.text = @"Syncing...";
    }
    if (status == bongSDKDataFetchStatusUploading) {
        _uploadingAlert.progressMessage.text = @"Uploading...";
    }
    if (status == bongSDKDataFetchStatusSucceed) {
        _isUploadingData = NO;
        //_uploadingAlert.progressMessage.text = @"Uploaded seccess!";
        [self performSelector:@selector(removeUploadingAlertView) withObject:nil afterDelay:0.5];
        NSDate *nowDate = [NSDate dateWithTimeInterval:-10 sinceDate:[NSDate date]];
        [[NSUserDefaults standardUserDefaults] setObject:nowDate forKey:LAST_SYNC_TIME];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        if([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable){
        [self syncdataToDataServer];
        }else{
                _dataServerErrorCode = -199;
                [self showNoInternet];
        }
    }
    if (status == bongSDKDataFetchStatusFailed) {
        _isUploadingData = NO;
        [_uploadingAlert removeFromSuperview];
        //重复操作
        if (error.code == 2) {
            
        }
        //n.bong.sdk.error Code=3 "The operation couldn’t be completed.
        //同步间隔需要大于5分钟
        else if (error.code == 3) {
            _bongErrorCode = 106;
            [self showFailSyn];
        }
        //连接设备失败
        else if (error.code == 4) {
            //            if (bleErrorTime <=1) {
            //                [self fetchbongIIData];
            //                bleErrorTime ++;
            //            }else{
            //                bongErrorCode = 106;
            //                [self showFailSyn];
            //            }
            _bongErrorCode = 106;
            [self showFailSyn];
        }else if (error.code == 5){
            _bongErrorCode = 106;
            NSLog(@"搜索设备失败");
            [self showFailSyn];
        }
        //网络连接失败
        else if (error.code == 10){
            _bongErrorCode = 111;
            [self showFailUpload];
        }
        else if(error.code == bongSDKErrorCodeBusy) {
            //ingore
            NSLog(@"bongSDKErrorCodeBusy");
            //未获得手环数据
        }else if (error.code == 9){
            //成功
            [self showSynSucess];
            
        }else if (error.code == -1009){
            _bongErrorCode = 110;
            [self showFailUpload];
        }
    }
}
/*
- (void)bongSDKDataFetchStatusDidChange:(bongSDKDataFetchStatus)status error:(NSError *)error {
    
    NSLog(@"手环数据同步状态更新 %d error %@", status, error);
    if (status == bongSDKDataFetchStatusSucceed ||
        status == bongSDKDataFetchStatusFailed) {
    }
    if (!self.isUploadingData) {
        self.uploadingAlert = [ProgressingView shareInstance];
        _uploadingAlert = [[[NSBundle mainBundle]loadNibNamed:@"ProgressingView" owner:self options:nil] lastObject];
        _uploadingAlert.frame = [[UIScreen mainScreen] bounds];
        [self.view addSubview:_uploadingAlert];
        self.isUploadingData = YES;
    }
    
    if(status == bongSDKDataFetchStatusConnecting){
        _uploadingAlert.progressMessage.text = @"Connecting...";
    }
    if (status == bongSDKDataFetchStatusFetching) {
        _uploadingAlert.progressMessage.text = @"Syncing...";
    }
    if (status == bongSDKDataFetchStatusUploading) {
        _uploadingAlert.progressMessage.text = @"Uploading...";
    }
    if (status == bongSDKDataFetchStatusSucceed) {
        _isUploadingData = NO;
        //_uploadingAlert.progressMessage.text = @"Uploaded seccess!";
        [self performSelector:@selector(removeUploadingAlertView) withObject:nil afterDelay:0.5];
        
        self.isFirstSynSuccess = YES;
        //同步成功，更新最后一次update时间
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *dateInfor = @{
                                    USERID : [defaults objectForKey:USERID],
                                    LASTUPDATEDDATE : self.lastSynDate
                                    };
        [defaults setValue:dateInfor forKey:LASTUPDATEDDATEUSERINFOR];
        BOOL isSynFinished = [self.currentSynDate isEqualToDate:[dateInfor objectForKey:LASTUPDATEDDATE]];
        //同步到最新时间
        if (isSynFinished) {
        if([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable){
            [self syncdataToDataServer];
            }else{
                    _dataServerErrorCode = -199;
                    [self showDataServerFail];
            }
            
        }else{
            NSArray *dateArr = [self getStartAndEndDates];
            NSDate *beginDate = [dateArr objectAtIndex:0];
            NSDate *endDate = [dateArr objectAtIndex:1];
            [bongSDK fetchbongIIDataWithStartDate:beginDate endDate:endDate];
        }
        

    }
    if (status == bongSDKDataFetchStatusFailed) {
        
        _isUploadingData = NO;
        [_uploadingAlert removeFromSuperview];
        if (self.isFirstSynSuccess) {
               // [self syncdataToDataServer];
            [self showPartialAttention];
        }else{
            //重复操作
            if (error.code == 2) {
                
            }
            //n.bong.sdk.error Code=3 "The operation couldn’t be completed.
            //同步间隔需要大于5分钟
            else if (error.code == 3) {
                _bongErrorCode = 106;
                [self showFailSyn];
            }
            //连接设备失败
            else if (error.code == 4) {
                //            if (bleErrorTime <=1) {
                //                [self fetchbongIIData];
                //                bleErrorTime ++;
                //            }else{
                //                bongErrorCode = 106;
                //                [self showFailSyn];
                //            }
                _bongErrorCode = 106;
                [self showFailSyn];
            }else if (error.code == 5){
                _bongErrorCode = 106;
                NSLog(@"搜索设备失败");
                [self showFailSyn];
            }
            //网络连接失败
            else if (error.code == 10){
                _bongErrorCode = 111;
                [self showFailUpload];
            }
            else if(error.code == bongSDKErrorCodeBusy) {
                //ingore
                NSLog(@"bongSDKErrorCodeBusy");
                //未获得手环数据
            }else if (error.code == 9){
                //成功
                [self showSynSucess];
                
            }else if (error.code == -1009){
                _bongErrorCode = 110;
                [self showFailUpload];
            }

        
        }

    }
}
 */

#pragma mark - bong handle

-(NSArray *)getStartAndEndDates{
    
    NSDate *currentDate = [NSDate date];
    self.currentSynDate = currentDate;
    NSDate *beginDate;
    NSDate *endDate;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    //第一次同步
    if ([defaults objectForKey:LASTUPDATEDDATEUSERINFOR] == nil)
    {
        NSDictionary *dateInfor = @{
                                    USERID : [defaults objectForKey:USERID],
                                    LASTUPDATEDDATE : currentDate
                                    };
        [defaults setObject:dateInfor forKey:LASTUPDATEDDATEUSERINFOR];
        beginDate = [[NSDate alloc] initWithTimeInterval:-60*10 sinceDate:[NSDate date]];
        endDate = currentDate;
    }
    else
    {
        NSDictionary *dateInfor = [NSDictionary dictionaryWithDictionary:[defaults objectForKey:LASTUPDATEDDATEUSERINFOR]];
        //对比userId_匹配
        if ([[defaults objectForKey:USERID] isEqualToString:[dateInfor objectForKey:USERID]])
        {
            NSTimeInterval timeInterval = [[dateInfor objectForKey:LASTUPDATEDDATE] timeIntervalSinceNow];
            float day = fabsf(timeInterval/(60*60*24));
            if (day>=7.0){
                beginDate = [[NSDate alloc] initWithTimeInterval:-60*60*24*7 sinceDate:[NSDate date]];
                endDate = [[NSDate alloc] initWithTimeInterval:-60*60*24*6 sinceDate:[NSDate date]];
            }else if (day>0 && day<1){
                beginDate = [dateInfor objectForKey:LASTUPDATEDDATE];
                endDate = currentDate;
            }
            else{
                beginDate = [dateInfor objectForKey:LASTUPDATEDDATE];
                endDate = [[NSDate alloc] initWithTimeInterval:60*60*24 sinceDate:[dateInfor objectForKey:LASTUPDATEDDATE]];
            }
        }
        else
        {
            //更换账户后第一次同步  对比userId_不匹配
            NSDictionary *dateInfor = @{
                                        USERID : [defaults objectForKey:USERID],
                                        LASTUPDATEDDATE : currentDate
                                        };
            [defaults setObject:dateInfor forKey:LASTUPDATEDDATEUSERINFOR];
            beginDate = [[NSDate alloc] initWithTimeInterval:-60*10 sinceDate:[NSDate date]];
            endDate = currentDate;
        }
    }
    self.lastSynDate = endDate;
    NSArray *dateArray = [[NSArray alloc]initWithObjects:beginDate,endDate,nil];
    return dateArray;
}


- (void)syncdataToDataServer{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defaults objectForKey:@"bongSDK"];
    NSString *UID = [dic objectForKey:USERDEFAULTSUID];
    NSString *accessToken = [dic objectForKey:USERDEFAULTSACCESSTOKEN];
    NSString *userName = [defaults objectForKey:USERID];
    
    [Syncdata setSyncdataAPIWithUID:UID andAccessToken:accessToken headerDataWithUserName:userName success:^(NSString *msg) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self showSynSucess];
            //update toady and week page
            [self updateViewContent:0 pageIndex:0];
            [self updateViewContent:0 pageIndex:1];
        });
    } failure:^(NSError *error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (error.code == 10) {
                _dataServerErrorCode = -188;
            }
            else{
                _dataServerErrorCode = error.code;
            }
            [self showGetDataFail];
        });
    }];
}

- (void)fetachbongIIData:(NSDate *)startDate endDate:(NSDate *)endDate{
      [bongSDK fetchbongIIDataWithStartDate:startDate endDate:endDate];
}

- (void)fetchbongIIData{
    NSDate *endDate = [NSDate date];
    // 1.2.5 固件以上，手环最多存储 7 天数据；1.2.5 固件以下此接口不可用
    NSDate *date = [[NSUserDefaults standardUserDefaults] objectForKey:LAST_SYNC_TIME];
    if (date) {
        //last succussful sysc to now
        NSDate *sixTimeIntervalDate = [NSDate dateWithTimeInterval:-60*6 sinceDate:endDate];
        NSDate *earlierDate = [sixTimeIntervalDate earlierDate:date];
        [bongSDK fetchbongIIDataWithStartDate:earlierDate endDate:nil];
    }else{
        //default fetch one day data
        [bongSDK fetchbongIIDataWithStartDate:[NSDate dateWithTimeInterval:-60*60*24 sinceDate:endDate] endDate:nil];
    }
    
}

- (void)showSynSucess{
    AlertView * alert = [AlertView shareInstance];
    alert = [[[NSBundle mainBundle]loadNibNamed:@"AlertView" owner:self options:nil] lastObject];
    alert.alertTitle.text = @"Thank You";
    alert.alertMessage.text = @"Your workout data is now synchronised.\n \n \n ";
    alert.frame = [[UIScreen mainScreen] bounds];
    [self.view addSubview:alert];
}
- (void)showDataServerFail{
    ConfirmView * confirm = [ConfirmView shareInstance];
    confirm = [[[NSBundle mainBundle]loadNibNamed:@"ConfirmView" owner:self options:nil] lastObject];
    confirm.tag = HSBC_DATA_SERVER;
    confirm.confirmTitle.text = @"Fail to get data from server";
    NSString *message = [NSString stringWithFormat:@"Problem occurs during getting data from server. Please check your network connection and retry.(%d)",_dataServerErrorCode];
    confirm.confirmMessage.text = message;
    confirm.frame = [[UIScreen mainScreen] bounds];
    confirm.confirmDelegate = self;
    [self.view addSubview:confirm];
}

- (void)showNoInternet{
    AlertView * alert = [AlertView shareInstance];
    alert = [[[NSBundle mainBundle]loadNibNamed:@"AlertView" owner:self options:nil] lastObject];
    alert.alertTitle.text = @"Oops!";
    alert.alertMessage.text = @"No internet connection. Please check your network. \n \n ";
    alert.frame = [[UIScreen mainScreen] bounds];
    [self.view addSubview:alert];
}

- (void)showGetDataFail{
    ConfirmView * confirm = [ConfirmView shareInstance];
    confirm = [[[NSBundle mainBundle]loadNibNamed:@"ConfirmView" owner:self options:nil] lastObject];
    confirm.tag = HSBC_DATA_SERVER;
    confirm.confirmTitle.text = @"Cannot retrieve new data";
    NSString *message = [NSString stringWithFormat:@"Problem occurs during getting new data from Bong.  Please try again.(%d)",_dataServerErrorCode];
    confirm.confirmMessage.text = message;
    confirm.frame = [[UIScreen mainScreen] bounds];
    confirm.confirmDelegate = self;
    [self.view addSubview:confirm];

}

- (void)showFailSyn{
    AlertView * alert = [AlertView shareInstance];
    alert = [[[NSBundle mainBundle]loadNibNamed:@"AlertView" owner:self options:nil] lastObject];
    alert.alertTitle.text = @"Cannot synchronise data";
    alert.alertMessage.text = [NSString stringWithFormat:@"Problem occurs during the synchronisation. Please touch Yes! button again on Bong to retry.(%d)", _bongErrorCode];
    alert.frame = [[UIScreen mainScreen] bounds];
    [self.view addSubview:alert];
}

- (void)showFailUpload{
    ConfirmView * confirm = [ConfirmView shareInstance];
    confirm = [[[NSBundle mainBundle]loadNibNamed:@"ConfirmView" owner:self options:nil] lastObject];
    confirm.confirmTitle.text = @"Cannot upload data";
    confirm.confirmMessage.text = [NSString stringWithFormat:@"Problem occurs during uploading data. Please check your network connection and retry.(%d)",_bongErrorCode];
    confirm.frame = [[UIScreen mainScreen] bounds];
    confirm.confirmDelegate = self;
    [self.view addSubview:confirm];
}

- (void)showPartialAttention{
    AlertView * alert = [AlertView shareInstance];
    alert = [[[NSBundle mainBundle]loadNibNamed:@"AlertView" owner:self options:nil] lastObject];
    alert.alertTitle.text = @"Oops!";
    alert.alertMessage.text = @"Data synchronisation is incomplete. Please touch Yes! button again on Bong to complete it.";
    alert.frame = [[UIScreen mainScreen] bounds];
    [self.view addSubview:alert];
}

#pragma mark -ConfirmDelegate-
- (void)confirmRetryPressed:(ConfirmView*)confirmView{
    if (confirmView.tag == HSBC_DATA_SERVER) {
        [self syncdataToDataServer];
    }else{
//        NSArray *dateArr = [self getStartAndEndDates];
//        NSDate *beginDate = [dateArr objectAtIndex:0];
//        NSDate *endDate = [dateArr objectAtIndex:1];
//        [bongSDK fetchbongIIDataWithStartDate:beginDate endDate:endDate];
        [self fetchbongIIData];
    }
}

-(void)removeUploadingAlertView{
    [_uploadingAlert removeFromSuperview];
}



@end
